package com.yantong.controller;

import com.alibaba.fastjson.JSONArray;
import com.yantong.constant.ActivityProductType;
import com.yantong.pojo.*;
import com.yantong.mapper.ActivityProductMapper;
import com.yantong.pojo.vo.ChooseProductVo;
import com.yantong.service.CategoryService;
import com.yantong.annotation.Log;
import com.yantong.exception.BDException;
import com.yantong.result.ResultVo;
import com.yantong.utils.PageUtils;
import com.yantong.service.DispatchService;
import com.yantong.enums.GroupTypeEnum;
import com.yantong.mapper.MarketingGroupSkuMapper;
import com.yantong.mapper.MarketingSeckillSkuMapper;
import com.yantong.service.MarketingGroupService;
import com.yantong.service.MarketingSeckillService;
import com.yantong.mapper.ProductSkuCentreMapper;
import com.yantong.service.ProductService;
import com.yantong.service.TicketService;
import com.yantong.pojo.vo.StoreFreechargeVo;
import com.yantong.mapper.StoreFreechargeMapper;
import com.yantong.service.CommanderListService;
import com.yantong.utils.ValidateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 营销活动管理
 *
 * @author kanghaixin
 * @date 2018/9/7.15:39
 */

@Controller
@RequestMapping("/marketing/manage")
public class MarketingController extends BaseController {
    private static final String prefix = "marketing";
    private static final Logger logger = LoggerFactory.getLogger(MarketingController.class);

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private MarketingSeckillService marketingSeckillService;


    @Autowired
    private MarketingGroupSkuMapper marketingGroupSkuMapper;

    @Autowired
    private CommanderListService commanderListService;

    @Autowired
    private MarketingGroupService marketingGroupService;

    @Autowired
    private TicketService ticketService;
    @Autowired
    private ActivityProductMapper activityProductMapper;
    @Autowired
    private StoreFreechargeMapper storeFreechargeMapper;

    /**
     * 跳转页面：秒杀页面
     *
     * @return
     */
    @GetMapping("/toSeckillPage")
    @RequiresPermissions("marketing:manage:seckill")
    public String toSeckillPage(Model model) {
        Category category = new Category();
        category.setParentid(0L);
        model.addAttribute("category", categoryService.getListCategory(category));
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/seckill";
    }

    /**
     * 跳转页面：秒杀页面
     *
     * @return
     */
    @GetMapping("/toAdd")
    @RequiresPermissions("marketing:manage:seckilladd")
    public String toAdd(Model model) {
        Category category = new Category();
        category.setParentid(0L);
        model.addAttribute("category", categoryService.getListCategory(category));

        return prefix + "/addSeckill";
    }


    /**
     * 跳转页面：选择商品页面
     *
     * @return
     */
    @GetMapping("/toChooseProduct")
    //@RequiresPermissions("marketing:manage:toChooseProduct")
    public String toChooseProduct(Model model) {
        ListMemberParams listMemberParams = new ListMemberParams();
        if (getUserCentreId() != null) {
            listMemberParams.setCentreId(getUserCentreId());
        }

        Map<String, Object> map = getCentreIdModelInfo();
        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
        model.addAttribute("teams", teams);
        model.addAllAttributes(map);
        return prefix + "/chooseProduct";
    }


    /**
     * 跳转页面：选择商品页面
     *
     * @return
     */
    @GetMapping("/toProductStockSetting")
    public String toProductStockSetting(Model model, @RequestParam("productCentreId") Long productCentreId) {
        model.addAttribute("productCentreId",productCentreId);
        return prefix + "/productStockSetting";
    }


    /**
     * 跳转页面：选择商品页面
     *
     * @return
     */
    @GetMapping("/toProductGroupStockSetting")
    public String toProductGroupStockSetting(Model model, @RequestParam("productCentreId") Long productCentreId) {
        model.addAttribute("productCentreId",productCentreId);
        return prefix + "/productGroupStockSetting";
    }

    /**
     * 跳转页面：选择优惠券页面
     *
     * @return
     */
    @GetMapping("/toChooseCoupon")
    public String toChooseCoupon(Model model, Integer packageNum) {
        ListMemberParams listMemberParams = new ListMemberParams();
        if (getUserCentreId() != null) {
            listMemberParams.setCentreId(getUserCentreId());
        }

        Map<String, Object> map = getCentreIdModelInfo();
        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
        model.addAttribute("teams", teams);
        model.addAttribute("packageNum", packageNum);
        model.addAllAttributes(map);
        return prefix + "/chooseCoupon";
    }


//    /**
//     * 列表 获取秒杀列表
//     * @param offset
//     * @param limit
//     * @param vo
//     * @return
//     * @author baolingyu
//     * @date 2018年11月5日-下午4:22:04
//     */
//    @GetMapping("/listAll")
//    @ResponseBody
//    @RequiresPermissions("product:manage:manage")
//    public PageUtils<MarketingSeckill> listAll(int offset, int limit, MarketingSeckillVo vo) {
//        vo.setCentreId(getUserCentreId());
//        vo.setTeamId(getUserTeamId());
//        return marketingSeckillService.listAllSeckill(offset, limit, vo);
//    }


    /**
     * 选择商品
     *
     */
    @GetMapping("/chooseProductList")
    @ResponseBody
//    @RequiresPermissions("productdata:manage")
    public PageUtils<ChooseProductRes> list(Model model, int offset, int limit, ChooseProductVo vo) {
        if(vo.getCentreId() == null){
            vo.setCentreId(getUserCentreId());
        }
        if(vo.getTeamId() == null){
            vo.setTeamId(getUserTeamId());
        }

        return marketingSeckillService.chooseProductList(offset, limit, vo);

    }

//
//    /**
//     * 数据保存 修改
//     * @return
//     */
//    @Log(module = "营销活动管理", operation = "新增或修改秒杀活动")
//    @ResponseBody
//    @RequiresPermissions("marketing:manage:seckilladd")
//    @PostMapping("/saveOrUpdate")
//    public ResultVo saveOrUpdate(@RequestBody MarketingSeckill params) {
//        if (params == null) {
//            return ResultVo.error();
//        }
//        //添加
//        if(params.getId()==null) {
//
//          int saveNum =  marketingSeckillService.saveMarketingSeckill(params);
//            if(saveNum>0) {
//                return ResultVo.ok();
//            }else {
//                return ResultVo.error();
//            }
//        }else {
//            //修改
//            int updNum = marketingSeckillService.updateMarketingSeckill(params);
//            if(updNum>0) {
//                return ResultVo.ok();
//            }else {
//                return ResultVo.error();
//            }
//        }
//    }


//    /**
//     * 跳转到编辑页面
//     *
//     * @param id
//     * @param model
//     * @return
//     * @author baolingyu
//     * @date 2018年8月28日-下午2:12:57
//     */
//    @RequiresPermissions("marketing:manage:seckilladd")
//    @GetMapping("/edit/{id}")
//    public String edit(@PathVariable Long id, Model model) {
//        Long centreId = getUserCentreId();
//        ListMemberParams listMemberParams = new ListMemberParams();
//        if (centreId != null) {
//            listMemberParams.setCentreId(centreId);
//        }
//        Map<String, Object> map = getCentreIdModelInfo();
//        List<Category> categorys = null;
//        //商户
////        if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
////            Category category = new Category();
////            category.setParentid(0L);
////            category.setCentreId(new Long(map.get("centreId").toString()));
////            categorys = categoryService.getListCategory(category);
////        } else {
////            categorys = categoryService.listCategorys(0L);
////        }
//        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
//        model.addAttribute("teams", teams);
//        //判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
//        Long teamId = getUserTeamId();
//        if (null != teamId) {
//            model.addAttribute("teamId", teamId);
//        }
//        MarketingSeckill marketingSeckill = marketingSeckillService.getMarketingSeckill(id);
//        model.addAttribute("seckill",marketingSeckill);
//        MarketingSeckillSkuExample example = new MarketingSeckillSkuExample();
//        example.createCriteria().andProductIdEqualTo(marketingSeckill.getId());
//        model.addAttribute("seckillSku", marketingSeckillSkuMapper.selectByExample(example));
//        model.addAllAttributes(map);
//        return prefix + "/editSeckill";
//    }


//    /**
//     * 删除标签
//     * @param id
//     * @return
//     */
//    @Log(module = "营销活动管理", operation = "删除秒杀")
//    @ResponseBody
//    @RequiresPermissions("marketing:manage:seckillRemove")
//    @PostMapping("/seckill/remove")
//    public ResultVo remove(Long id) {
//        if (id == null) {
//            return ResultVo.error();
//        }
//
//        marketingSeckillService.removeSeckill(id);
//
//        return ResultVo.ok();
//    }


//    @GetMapping("/listAllSkuByProductId")
//    @ResponseBody
////    @RequiresPermissions("product:manage:manage")
//    public PageUtils<ProductSkuCentre> listAllSkuByProductId(@RequestParam("productCentreId") Long productCentreId) {
//        PageUtils<ProductSkuCentre> pageUtils = new PageUtils<>();
//        List<ProductSkuCentre> list = productSkuCentreMapper.getByProductId(productCentreId);
//        pageUtils.setTotal(list == null ? 0:list.size());
//        pageUtils.setRows(list == null ? Collections.EMPTY_LIST:list);
//        return  pageUtils;
//    }
//
//    @GetMapping("/listAllSeckillSkuByProductId")
//    @ResponseBody
////    @RequiresPermissions("product:manage:manage")
//    public PageUtils<MarketingSeckillSku> listAllSeckillSkuByProductId(@RequestParam("productCentreId") Long productCentreId) {
//        PageUtils<MarketingSeckillSku> pageUtils = new PageUtils<>();
//        List<MarketingSeckillSku> list = marketingSeckillService.listMarketingSeckillSkuByProductId(productCentreId);
//        pageUtils.setTotal(list == null ? 0:list.size());
//        pageUtils.setRows(list == null ? Collections.EMPTY_LIST:list);
//        return  pageUtils;
//    }


    /***********************团购*************************************/


    /**
     * 跳转页面：拼团页面
     *
     * @return
     */
    @GetMapping("/toGroupPage")
    @RequiresPermissions("marketing:manage:groupManage")
    public String toGroupPage(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/group";
    }

    /**
     * 跳转页面：新增拼团页面
     *
     * @return
     */
    @GetMapping("/toGroupAdd")
    @RequiresPermissions("marketing:manage:groupAdd")
    public String toGroupAdd(Model model) {
        model.addAttribute("ytMallFlag",true);
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/addGroup";
    }


    /**
     * 列表 获取团购列表
     * @param offset
     * @param limit
     * @param vo
     * @return
     * @author baolingyu
     * @date 2018年11月5日-下午4:22:04
     */
    @GetMapping("/grouplistAll")
    @ResponseBody
    @RequiresPermissions("marketing:manage:groupManage")
    public PageUtils<MarketingGroup> grouplistAll(Model model, int offset, int limit, MarketingGroup vo) {
        model.addAllAttributes(getCentreIdModelInfo());
        vo.setCentreId(getUserCentreId());
        vo.setTeamId(getUserTeamId());
        return marketingGroupService.listAllGroup(offset, limit, vo);
    }

    @GetMapping("/listAllGroupByProductId")
    @ResponseBody
//    @RequiresPermissions("product:manage:manage")
    public PageUtils<MarketingGroupSku> llSeckillSkuByProductId(@RequestParam("productCentreId") Long productCentreId) {
        PageUtils<MarketingGroupSku> pageUtils = new PageUtils<>();
        List<MarketingGroupSku> list = marketingGroupService.listMarketingGroupSkuByProductId(productCentreId);
        pageUtils.setTotal(list == null ? 0:list.size());
        pageUtils.setRows(list == null ? Collections.EMPTY_LIST:list);
        return  pageUtils;
    }


    /**
     * 数据保存 修改
     * @return
     */
    @Log(module = "营销活动管理", operation = "新增或修改团购活动")
    @ResponseBody
    @RequiresPermissions("marketing:manage:groupAdd")
    @PostMapping("/group/saveOrUpdate")
    public ResultVo groupSaveOrUpdate(@RequestBody MarketingGroup params) {
        if (params == null) {
            return ResultVo.error();
        }
        if (GroupTypeEnum.SNAP_UP.getCode().equals(params.getType())) {
            if(params.getNeedJoinGroupNum() - params.getWinningNumber() < 1){
                throw new BDException("中奖人数不能大于拼团总人数减1");
            }
        }
        //拼团大礼包
        if( params.getMarketingGroupType() == null ){
            params.setMarketingGroupType(0);
        }
        if( params.getMarketingGroupType() == 1 ){
            //判断大礼包下面有没有  优惠券和商品
            ActivityProductExample example = new ActivityProductExample();
            example.createCriteria().andActivityIdEqualTo(params.getProductId()).andTypeEqualTo(ActivityProductType.FREE_CHARGE.getType());
            List<ActivityProduct> list = activityProductMapper.selectByExample(example);
            List<String> couponIdList = new ArrayList<>();
            list.forEach(s -> {
                if(ValidateUtil.isNotEmptyString(s.getCouponIds())){
                    String[] strs = s.getCouponIds().split(",");
                    Collections.addAll(couponIdList,strs);
                }
            });
             BigDecimal bigGiftAmountSum = BigDecimal.ZERO;
            List<StoreFreechargeVo> storeFreechargeVoList = storeFreechargeMapper.selectByIdIn(couponIdList);
            for (StoreFreechargeVo model : storeFreechargeVoList){
                Integer refId = model.getRefId() == null ? 0 : model.getRefId();
                Ticket ticket = ticketService.getByKey(refId.longValue());
                if( ticket != null ){
                    bigGiftAmountSum = bigGiftAmountSum.add(ticket.getBigGiftAmount()==null?BigDecimal.ZERO:ticket.getBigGiftAmount());
                }
            }
            bigGiftAmountSum = bigGiftAmountSum.add(bigGiftAmountSum.divide(new BigDecimal("100")));
            BigDecimal vipPrice = params.getVipPrice();
            BigDecimal groupPrice = params.getGroupPrice();
            if( vipPrice.compareTo(bigGiftAmountSum) < 0 || groupPrice.compareTo(bigGiftAmountSum) < 0 ){
                throw new BDException("活动价格和vip价格都必须大于优惠券的核销价格总和+总和的1%");
            }

        }


        //添加
        if(params.getId()==null) {

            int saveNum =  marketingGroupService.saveMarketingGroup(params);
            if(saveNum>0) {
                return ResultVo.ok();
            }else {
                return ResultVo.error();
            }
        }else {
            //修改
            int updNum = marketingGroupService.updateMarketingGroup(params);
            if(updNum>0) {
                return ResultVo.ok();
            }else {
                return ResultVo.error();
            }
        }
    }

    /**
     * 删除标签
     * @param id
     * @return
     */
    @Log(module = "营销活动管理", operation = "删除团购活动")
    @ResponseBody
    @RequiresPermissions("marketing:manage:groupRemove")
    @PostMapping("/group/remove")
    public ResultVo groupRemove(Long id) {
        if (id == null) {
            return ResultVo.error();
        }

        marketingGroupService.removeGroup(id);

        return ResultVo.ok();
    }


    /**
     * 跳转到编辑页面
     *
     * @param id
     * @param model
     * @return
     * @author baolingyu
     * @date 2018年8月28日-下午2:12:57
     */
    @RequiresPermissions("marketing:manage:groupAdd")
    @GetMapping("/group/edit/{id}")
    public String groupEdit(@PathVariable Long id, Model model) {
        Long centreId = getUserCentreId();
        ListMemberParams listMemberParams = new ListMemberParams();
        if (centreId != null) {
            listMemberParams.setCentreId(centreId);
        }
        Map<String, Object> map = getCentreIdModelInfo();
        List<Category> categorys = null;
        //商户
//        if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
//            Category category = new Category();
//            category.setParentid(0L);
//            category.setCentreId(new Long(map.get("centreId").toString()));
//            categorys = categoryService.getListCategory(category);
//        } else {
//            categorys = categoryService.listCategorys(0L);
//        }
        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
        model.addAttribute("teams", teams);
        //判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
        Long teamId = getUserTeamId();
        if (null != teamId) {
            model.addAttribute("teamId", teamId);
        }
        MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(id);

        List<TicketDTO> list;
        List<Ticket> ticketList = new ArrayList<>();
        if(ValidateUtil.isNotEmptyString(marketingGroup.getTicketIds())){
            list = JSONArray.parseArray(marketingGroup.getTicketIds(),TicketDTO.class);
            for(TicketDTO ticketDTO:list){
                Ticket ticket = ticketService.getByKey(ticketDTO.getId());
                ticketList.add(ticket);
            }
            marketingGroup.setTicketList(list);
            marketingGroup.setTicList(ticketList);
        }

        model.addAttribute("group",marketingGroup);
        MarketingGroupSkuExample example = new MarketingGroupSkuExample();
        example.createCriteria().andProductIdEqualTo(id);
        model.addAttribute("groupSku", marketingGroupSkuMapper.selectByExample(example));
        model.addAllAttributes(map);
        model.addAttribute("ytMallFlag",true);
        return prefix + "/editGroup";
    }
}
